package com.filter;

import com.utils.Pool;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class SysFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // 获取后端请求地址
        String url = request.getRequestURL().toString();
        HttpSession session = request.getSession();
        Object user = session.getAttribute(Pool.SESSION_USER);

        // 放行条件（登录接口、登录后没有注销情况下）
        if (url.contains("login") || user != null) {
            chain.doFilter(req, resp);
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未经授权，请先登录！");
        }

    }


}
